<template>
  <div class="details">
    <div class="forbid-height" v-if="pageShow == true" @click="forbidHit"></div>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="课程名称" prop="name" class="form-item">
        <el-input v-model="ruleForm.name" placeholder="请输入课程名称"></el-input>
      </el-form-item>

      <el-form-item label="课程分类" prop="classifyId" class="form-item">
        <el-select v-model="ruleForm.classifyId" placeholder="请选择课程分类" clearable>
          <el-option v-for="item in classify1Options" :key="item.courseClassifyId" :label="item.courseClassifyName"
            :value="item.courseClassifyId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程封面" prop="cover" class="form-banner">
        <div class="banners">
          <el-upload action="https://api-qingchuang.xmw1688.com/common/upload" :show-file-list="false"
            :on-success="handleAvatarSuccessCover" class="img">
            <div class="img">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>

          <div class="imgs" v-if="ruleForm.cover != '' && ruleForm.cover != null">
            <el-image :src="ruleForm.cover" :preview-src-list="srcList0"></el-image>

            <i class="el-icon-delete" style="
                position: absolute;
                top: 10px;
                right: 10px;
                font-size: 20px;
                cursor: pointer;
                color: red;
              " @click="handleRemoveCover"></i>
          </div>
        </div>

        <div class="text">限制上传一张</div>
      </el-form-item>

      <el-form-item label="课程图片" prop="banner" class="form-banner">
        <div class="banners">
          <el-upload action="https://api-qingchuang.xmw1688.com/common/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" class="img" :limit="9">
            <div class="img">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>

          <div class="imgs" v-for="(item, index) in ruleForm.banner" :key="index">
            <el-image :src="item" :preview-src-list="srcList1"></el-image>

            <i class="el-icon-delete" style="
                position: absolute;
                top: 10px;
                right: 10px;
                font-size: 20px;
                cursor: pointer;
                color: red;
              " @click="handleRemove(index)"></i>
          </div>
        </div>
        <div class="text">
          最多可上传9张，图片将在课程详情页轮播展示
        </div>
      </el-form-item>

      <el-form-item label="课程类型" prop="type" class="form-item">
        <el-radio v-for="(item, index) in 2" :key="index" v-model="ruleForm.type" :label="index" @change="radioChange">
          {{ index == 0 ? "免费" : "付费" }}
        </el-radio>
      </el-form-item>

      <el-form-item label="是否推荐" prop="isIndex" class="form-item">
        <el-radio v-for="(item, index) in 2" :key="index" v-model="ruleForm.isIndex" :label="index"
          @change="isIndexChange">
          {{ index == 0 ? "否" : "是" }}
        </el-radio>
      </el-form-item>


      <el-form-item label="销售价（元）" :prop="ruleForm.type == 0 ? '' : 'price'" class="form-item">
        <el-input v-model="ruleForm.price" placeholder="请输入销售价（元）" :disabled="ruleForm.type == 0 ? true : false"
          clearable></el-input>
      </el-form-item>

      <el-form-item label="虚拟销量" prop="virtual" class="form-item">
        <el-input v-model="ruleForm.virtual" placeholder="请输入虚拟销量" clearable></el-input>

        <div class="text">虚拟销量+真实销量为课程展示在前台的销量</div>
      </el-form-item>

      <el-form-item label="下载链接" prop="link" class="form-item">
        <el-input v-model="ruleForm.link" placeholder="请输入下载链接" clearable></el-input>
      </el-form-item>

      <el-form-item label="提取码" prop="extract" class="form-item">
        <el-input v-model="ruleForm.extract" placeholder="请输入提取码" clearable></el-input>
      </el-form-item>

      <el-form-item label="课程状态" prop="isStatus" class="form-item">
        <el-select v-model="ruleForm.isStatus" placeholder="请选择" clearable>
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程详情页" prop="step" class="form-editor">
        <wang-edit ref="wangEditorRef" v-if="editShow" :editorParams="ruleForm.editorParams" />
      </el-form-item>

      <el-form-item>
        <div class="form-button">
          <div class="list" @click="addClose('ruleForm')">取消</div>
          <div class="list" @click="addSave('ruleForm')">保存</div>
          <!-- <div class="list" @click="addStatusSave('ruleForm')">保存并上架</div> -->
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import WangEdit from "@/components/wangEditor/RichTextEditor.vue";

import { courseClassifyList, courseListId, courseListAdd } from "@/api/course";

var throttle = require("@/utils/throttle"); // 防抖

export default {
  components: {
    WangEdit,
  },
  data() {
    return {
      id: "",
      intersectionActive: 0,
      pageShow: false, // 是否可修改
      //-------------
      commonObj: {},
      ruleForm: {
        name: "",
        classifyId: "",
        classifyName: "",
        cover: "",
        banner: [],
        type: 0,
        price: "",
        virtual: "",
        link: "",
        extract: "",
        editorParams: {
          content: "", // 富文本内容
          placeholder: "请填写内容", // 富文本占位内容
          uploadImageUrl: "/file", // 富文本上传图片的地址
          height: "400px", // 富文本最小高度
          isDisabled: false, // 富文本是否禁用
        },
        step: "",
        //----------------------
        isIndex: 0,
        isStatus: '',
      },
      rules: {
        name: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
        classifyId: [
          { required: true, message: "请输入选择课程分类", trigger: "blur" },
        ],
        cover: [
          { required: true, message: "请输入上传课程封面", trigger: "blur" },
        ],

        banner: [
          {
            required: true,
            message: "请输入上传课程图片/视频",
            trigger: "blur",
          },
        ],
        type: [{ required: true, message: "请选择课程类型", trigger: "blur" }],

        price: [
          { required: true, message: "请输入销售价（元）", trigger: "blur" },
        ],
        virtual: [
          { required: true, message: "请输入虚拟销量", trigger: "blur" },
        ],
        link: [{ required: true, message: "请输入下载链接", trigger: "blur" }],
        extract: [{ required: true, message: "请输入提取码", trigger: "blur" }],
        step: [
          { required: true, message: "请输入课程详情页", trigger: "blur" },
        ],
        isIndex: [
          { required: true, message: "请选择课程类型", trigger: "blur" },
        ],
        isStatus: [
          { required: true, message: "请输入选择课程状态", trigger: "change" },
        ],
      },

      //------------
      classifyOptions: [],
      classify1Options: [],
      statusOptions: [ // 0草稿 1已上架 2已下架 3已回收
        {
          label: '草稿',
          value: 0,
        },
        {
          label: '上架',
          value: 1,
        },
        {
          label: '下架',
          value: 2,
        },
        {
          label: '回收',
          value: 3,
        },
      ],
      //-----------
      editShow: false,
      srcList0: [],
      srcList1: [],
    };
  },
  created() {
    this.pageShow = this.$route.query.soucre == 1 ? true : false;

    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.courseListIdMet();
    }

    this.courseClassifyListMet();
  },
  mounted() {
    this.editShow = true;
  },
  methods: {
    forbidHit() {
      this.$message.error("当前详情页，禁止修改");
    },
    courseClassifyListMet() {
      let params = {
        isIndex: 1,
        pageSize: 1000,
        pageNo: 1,
      };

      courseClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          this.classifyOptions = res.resultData.courseClassifyList;
          this.courseClassifyListMet1();

        }
      });
    },
    courseClassifyListMet1() {
      let params = {
        isIndex: 0,
        pageSize: 1000,
        pageNo: 1,
      };

      courseClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          this.classify1Options = this.classifyOptions.concat(res.resultData.courseClassifyList)

        }
      });
    },
    courseListIdMet() {
      let params = this.id;

      courseListId(params).then((res) => {
        if (res.errorCode == null) {
          this.commonObj = res.resultData;
          //-------------------------------------
          this.ruleForm.name = res.resultData.courseName;
          this.ruleForm.classifyId = res.resultData.courseClassifyId;

          this.ruleForm.classifyName = res.resultData.courseClassifyName;

          this.ruleForm.cover = res.resultData.courseIcon;
          this.srcList0 = [res.resultData.courseIcon];

          this.ruleForm.banner = res.resultData.courseImage.split(";");
          this.srcList1 = res.resultData.courseImage.split(";");

          this.ruleForm.type = res.resultData.priceType;
          this.ruleForm.price = Number(res.resultData.price / 100);

          this.ruleForm.virtual = res.resultData.purchaseNum;
          this.ruleForm.isIndex = res.resultData.isIndex
          this.ruleForm.isStatus = res.resultData.isStatus
          this.ruleForm.link = res.resultData.courseUrl;
          this.ruleForm.extract = res.resultData.coursePassword;
          this.ruleForm.editorParams.content = res.resultData.courseContent;
        }
      });
    },
    //---------上传
    handleAvatarSuccessCover(res, file) {
      this.ruleForm.cover = res.resultData;
      this.srcList0 = [res.resultData];
    },
    handleRemoveCover() {
      if (this.pageShow == true) {
        this.forbidHit();
        return;
      }

      this.ruleForm.cover = "";
    },

    handleAvatarSuccess(res, file) {
      if (this.ruleForm.banner.length < 9) {
        this.ruleForm.banner.push(res.resultData);

        this.srcList1 = this.ruleForm.banner;
      } else {
        this.$message.error(
          "最多可上传9张，图片将在商品详情页轮播展示！"
        );
      }
    },
    handleRemove(index) {
      if (this.pageShow == true) {
        this.forbidHit();
        return;
      }

      this.ruleForm.banner.splice(index, 1);
    },

    radioChange(e) {
      this.ruleForm.type = e;
      this.ruleForm.price = "";
    },
    isIndexChange(e) {
      this.ruleForm.isIndex = e;
    },
    //-------
    setHtml(html) {
      // 回显富文本框中内容
      let _this = this;
      this.$nextTick(() => {
        // 此处用来解决富文本编辑器未完全加载的问题
        setTimeout(() => {
          _this.$refs.wangEditorRef.setEditorHtml(html);
        }, 200);
      });
    },
    getHtml() {
      this.$refs.wangEditorRef.getEditorHtml();
    },
    //------------

    //-------------------------------------------------------------------------------------------
    addSave: throttle.throttle(function (formName) {
      this.ruleForm.step =
        this.$refs.wangEditorRef.getEditorHtml() == "<p><br></p>"
          ? ""
          : this.$refs.wangEditorRef.getEditorHtml();

      let num = this.ruleForm.isStatus == 0 ? 3 : this.ruleForm.isStatus == 1 ? 1 : this.ruleForm.isStatus == 2 ? 2 : this.ruleForm.isStatus == 3 ? 4 : ''

      //----------------
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            courseId: this.id,
            courseName: this.ruleForm.name,
            courseClassifyId: this.ruleForm.classifyId,
            courseClassifyName: this.ruleForm.classifyName,
            courseIcon: this.ruleForm.cover,
            courseImage: this.ruleForm.banner.join(";"),
            priceType: this.ruleForm.type,
            price: Number(this.ruleForm.price * 100),
            purchaseNum: Number(this.ruleForm.virtual),
            courseUrl: this.ruleForm.link,
            coursePassword: this.ruleForm.extract,
            courseContent: this.ruleForm.step,
            isStatus: this.ruleForm.isStatus,
            isIndex: this.ruleForm.isIndex
          };

          courseListAdd(params).then((res) => {
            if (res.errorCode == null) {
              if (this.id == "") {
                this.$message.success("新增课程成功！");
              } else {
                this.$message.success("编辑课程成功！");
              }

              setTimeout(() => {
                this.$router.push({
                  path: "/course/table/list?index=" + this.ruleForm.isStatus + '&source=' + num,
                });

                this.$refs[formName].resetFields();
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    }, 3000),
    addStatusSave: throttle.throttle(function (formName) {
      this.ruleForm.step =
        this.$refs.wangEditorRef.getEditorHtml() == "<p><br></p>"
          ? ""
          : this.$refs.wangEditorRef.getEditorHtml();

      //----------------
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            courseId: this.id,
            courseName: this.ruleForm.name,
            courseClassifyId: this.ruleForm.classifyId,
            courseClassifyName: this.ruleForm.classifyName,
            courseIcon: this.ruleForm.cover,
            courseImage: this.ruleForm.banner.join(";"),
            priceType: this.ruleForm.type,
            price: Number(this.ruleForm.price * 100),
            purchaseNum: Number(this.ruleForm.virtual),
            courseUrl: this.ruleForm.link,
            coursePassword: this.ruleForm.extract,
            courseContent: this.ruleForm.step,
            isStatus: 1,
          };

          courseListAdd(params).then((res) => {
            if (res.errorCode == null) {
              if (this.id == "") {
                this.$message.success("新增课程成功！");
              } else {
                this.$message.success("编辑课程成功！");
              }

              setTimeout(() => {
                this.$router.push({
                  path: "/course/table/list",
                });

                this.$refs[formName].resetFields();
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    }, 3000),
    addClose(formName) {
      this.$router.push({
        path: "/course/table/list",
      });

      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
@import url("@/assets/css/common.less");

.details {
  position: relative;

  .forbid-height {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 10;
    display: flex;
  }

  /deep/ .el-form-item__label {
    text-align: left;
    width: 120px;
  }

  /deep/ .el-form-item__content {
    width: 75%;
    margin-left: 0 !important;
  }

  .form-item {
    width: 500px;
    display: flex;

    /deep/ .el-cascader {
      width: 100%;
    }

    /deep/ .el-input {
      width: 100%;
    }

    /deep/ .el-select {
      width: 100%;
    }
  }

  .form-banner {
    /deep/ .el-form-item__error {
      left: 120px;
    }

    .banners {
      /deep/ .el-form-item__content {
        display: flex;
      }

      display: flex;

      .img {
        width: 100px;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #ccc;
        border-radius: 5px;
        position: relative;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .imgs {
        width: 100px;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #ccc;
        margin-left: 10px;
        border-radius: 5px;
        position: relative;
        z-index: 11;
        cursor: pointer;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .text {
      color: #999;
      margin-left: 120px;
    }
  }

  .text {
    color: #999;
  }

  .form-editor {
    /deep/ .el-form-item__content {
      width: 64%;
      margin-left: 120px !important;
    }

    margin-top: 40px;
    width: 70%;
  }

  .form-button {
    display: flex;
    align-items: center;
    margin-left: 120px !important;

    /deep/ .el-form-item__content {
      line-height: 0;
      width: 64%;
    }

    .list {
      background: #3da8f5;
      color: #fff;
      font-size: 16px;
      margin-right: 20px;
      border-radius: 5px;
      min-width: 80px;
      height: 35px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      padding: 0 20px;
      box-sizing: border-box;
    }

    .list:first-child {
      background: #808080;
      z-index: 11;
    }
  }
}
</style>